// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/client"
	"hotgo/utility/tradeDate"
	"io"
	url2 "net/url"
	"strings"
	"time"
)

func init() {
	cron.Register(StockRank)
}

// StockRank 测试任务（无参数）
var StockRank = &cStockRank{name: "stock_rank"}
var StockRankUrls = map[string]string{
	"开盘啦":    "https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=GetHotPHB&st=50&apiv=w29&Type=1&c=StockBidYiDong&PhoneOSNew=1&DeviceID=20ad85ca-becb-3bed-b3d4-30032a0f5923",
	"东财-飙升榜": "http://127.0.0.1:8000/api/public/stock_hot_up_em",
	"东财-人气榜": "http://127.0.0.1:8000/api/public/stock_hot_rank_em",
	"百度热搜股":  fmt.Sprintf("http://127.0.0.1:8000/api/public/stock_hot_search_baidu?symbol=%s&date=%s", url2.QueryEscape("A股"), tradeDate.GetLatestDay()),
}

type StockKPLRankResp struct {
	ErrCode string          `json:"errcode"`
	List    []StockRankItem `json:"list"`
}

type StockEMRankResp struct {
	Rank int    `json:"当前排名"`
	Code string `json:"代码"`
	Name string `json:"股票名称"`
}

type StockBDRankResp struct {
	Name string `json:"股票名称"`
	Code string `json:"市场代码"`
}

type StockRankItem []any

type cStockRank struct {
	name string
}

func (c *cStockRank) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cStockRank) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	for source, stockRankUrl := range StockRankUrls {
		time.Sleep(1 * time.Second)
		httpClient := client.GetClient()
		response, err := httpClient.Get(ctx, fmt.Sprintf("%s", stockRankUrl))
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
			continue
		}
		defer response.Body.Close()
		body, err := io.ReadAll(response.Body)
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
			continue
		}
		switch source {
		case "开盘啦":
			var resp StockKPLRankResp
			err = json.Unmarshal(body, &resp)
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
				continue
			}
			if resp.ErrCode == "0" {
				for _, emResp := range resp.List {
					var editInp = &sysin.StockRankEditInp{}
					code, _ := emResp[0].(string)
					name, _ := emResp[1].(string)
					rank, _ := emResp[4].(float64)
					editInp.Source = source
					editInp.Name = name
					editInp.Code = code
					editInp.Rank = int(rank)
					err := service.SysStockRank().Edit(ctx, editInp)
					if err != nil {
						parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
						continue
					}
				}
			}
		case "东财-飙升榜", "东财-人气榜":
			var resp []StockEMRankResp
			err = json.Unmarshal(body, &resp)
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
				continue
			}
			for _, emResp := range resp {
				var editInp = &sysin.StockRankEditInp{}
				code := emResp.Code
				code = strings.TrimPrefix(code, "SH")
				code = strings.TrimPrefix(code, "SZ")
				editInp.Source = source
				editInp.Name = emResp.Name
				editInp.Code = code
				editInp.Rank = emResp.Rank
				err := service.SysStockRank().Edit(ctx, editInp)
				if err != nil {
					parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
					continue
				}
			}
		case "百度热搜股":
			var resp []StockBDRankResp
			err = json.Unmarshal(body, &resp)
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
				continue
			}
			for rank, emResp := range resp {
				var editInp = &sysin.StockRankEditInp{}
				editInp.Source = source
				editInp.Name = emResp.Name
				editInp.Code = emResp.Code
				editInp.Rank = rank
				err := service.SysStockRank().Edit(ctx, editInp)
				if err != nil {
					parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
					continue
				}
			}
		}
	}

	return
}
